package com.cc.data_explore.logic.mybatis;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cc
 * @version 1.0
 * @since 2025/3/29
 */
public class DbHelper {
    public static final String MAIN_DB_NAME = "data_explore";
    public static final String MAIN_MAPPER_PATH = "com.cc.data_explore.logic.mybatis.mapper.main";
    public static final String U_MAPPER_PATH = "com.cc.data_explore.logic.mybatis.mapper.sub";
    private static final DbHelper DB_HELPER = new DbHelper();
    private final Map<String, Db> DB_MAP_POOL = new HashMap<>();
    public final StringProperty DB_NAME = new SimpleStringProperty();

    public static DbHelper getInstance() {
        return DB_HELPER;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        String value = DB_NAME.getValue();
        if (value == null) {
            return null;
        }
        return getSqlSessionFactory(value);
    }

    public SqlSessionFactory getSqlSessionFactory(String dbName) {
        Db db = getDb(dbName);
        if (db == null) {
            return null;
        }
        return db.getSqlSessionFactory();
    }

    public void putDb(String dbName, Db db) {
        DB_MAP_POOL.put(dbName, db);
    }

    public Db getDb(String dbName) {
        return DB_MAP_POOL.get(dbName);
    }

    public void remDb(String dbName) {
        Db db = DB_MAP_POOL.remove(dbName);
        if (db != null) {
            db.close();
        }
    }
}
